package com.spacing.app;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;

import org.codechimp.apprater.AppRater;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;
import com.senseilearning.english.R;
import com.spacing.app.data.Chapters;
import com.spacing.app.data.Section;

public class DisplayMultipleChoiceActivity extends SherlockActivity implements OnInitListener {
	boolean spacing = false;
	Animation shake;

	int count_1;
	int count_2;
	long answerTime;
	// TTS object
	// private TextToSpeech myTTS;
	// status check code
	private int MY_DATA_CHECK_CODE = 0;
	Section section;
	CountDownTimer countDownTimer;
	Integer[] order = { 0, 1, 2, 3 };
	Question q;
	SchemaHelper schemahelper; // for sqlite
	Spacer spacer;
	Timer timer;
	boolean stop = true;
	Button[] buttons_answer;
	TextView[] tvbutton_answer;
	ImageView imageview_progress_1;
	ImageView imageview_progress_2;
	TextView textViewStack;
	TextView textview_question;
	TextView textview_new_word_1;
	TextView textview_new_word_2;
	TextView textview_time;
	int indexLanguage1;
	int indexLanguage2;
	
	
	int stack;
	Animation animationFadeIn;
	Animation animationFadeOut;
	Typeface font_robo_l;
	Typeface font_robo_m;
	Typeface font_robo_m_i;
	boolean doubleBackToExitPressedOnce;
	boolean switchlanguage;
	
	private TextToSpeech tts;
	
	// Walkthrough variables
	Boolean firstSession;
	String imageFilePrefix = "mc0";
	int nrOfWalkthroughPages = 3;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		ActionBar ab = getSupportActionBar();
		ab.setTitle(getString(R.string.multiplechoice));
		super.onCreate(savedInstanceState);

		final SharedPreferences sp = getSharedPreferences("my_db", Context.MODE_PRIVATE);
		
		firstSession = sp.getBoolean("firstMCView", true);
		
		if(firstSession) { //show the walkthrough
			
			Intent intent = new Intent(this, WalkthroughActivity.class);
			intent.putExtra("filePrefix", imageFilePrefix.toString());
			intent.putExtra("nrOfPages", nrOfWalkthroughPages);
    		startActivity(intent);
			
			SharedPreferences.Editor editor = sp.edit();
			editor.putBoolean("firstMCView", false);
//			editor.putString("lastActivity", getClass().getName());
			editor.commit();
//			finish();
		}
		setViewMultipleChoice();

		Intent intent = getIntent();
		section = (Section) intent.getSerializableExtra("section");
		tts = new TextToSpeech(this, this);

		spacer = new Spacer(section.getWords(), new SchemaHelper(this), "MultipleChoice");
		q = new Question(section, spacer);
		schemahelper = new SchemaHelper(this);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String currentDateandTime = sdf.format(new Date());
		schemahelper.addDatePracticed(section.getName(), currentDateandTime);

		Intent checkTTSIntent = new Intent();
		checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
		clickNext(null);
	}

	
	//onStart and onStop are now only used for calling the analytics methods
	@Override
	public void onStart(){
		super.onStart();
		//New code for this method must be added before the easytracker line!
		EasyTracker.getInstance().activityStart(this);
		Tracker tracker = EasyTracker.getTracker();
		tracker.setCustomDimension(2, section.getName()); //misschien ook een chapter meegeven? dimension id voor een chapter is 1, voor een section 2.
		tracker.sendView();
	}
	
	@Override
	public void onStop() {
		super.onStop();
		//New code for this method must be added before the easytracker line!
		EasyTracker.getInstance().activityStop(this);
	}
	
	/*
	 * sets the view needed for multiple choice
	 */
	public void setViewMultipleChoice() {
		setContentView(R.layout.multiple_choice);
		TextView tvbutton1 = (TextView) findViewById(R.id.tvbutton1);
		TextView tvbutton2 = (TextView) findViewById(R.id.tvbutton2);
		TextView tvbutton3 = (TextView) findViewById(R.id.tvbutton3);
		TextView tvbutton4 = (TextView) findViewById(R.id.tvbutton4);
		Button button1 = (Button) findViewById(R.id.button1);
		Button button2 = (Button) findViewById(R.id.button2);
		Button button3 = (Button) findViewById(R.id.button3);
		Button button4 = (Button) findViewById(R.id.button4);
		textview_question = (TextView) findViewById(R.id.textView1);
		textViewStack = (TextView) findViewById(R.id.stack);
		textview_time = (TextView) findViewById(R.id.textTime);
		imageview_progress_1 = (ImageView) findViewById(R.id.imageView1);
		imageview_progress_2 = (ImageView) findViewById(R.id.imageView2);

		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade);
		animationFadeOut = AnimationUtils.loadAnimation(this, R.anim.fadeout);
		font_robo_l = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
		font_robo_m_i = Typeface.createFromAsset(getAssets(), "fonts/Roboto-MediumItalic.ttf");
		font_robo_m = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Medium.ttf");

		button1.setTypeface(font_robo_l);
		button2.setTypeface(font_robo_l);
		button3.setTypeface(font_robo_l);
		button4.setTypeface(font_robo_l);
		textview_question.setTypeface(font_robo_m_i);

		Button[] tmp = { button1, button2, button3, button4 };
		TextView[] tmp2 = { tvbutton1, tvbutton2, tvbutton3, tvbutton4 };
		buttons_answer = tmp;
		tvbutton_answer = tmp2;

	}


	
	/*
	 * user clicks on next image
	 */
	public void clickNext(View view) {
		if (spacer.isComplete() && stop) {
			showDialog();
		}

		showButtons();
		if(q.nextQuestion()){
			indexLanguage1 = 0;
			indexLanguage2 = 1;
		} else{
			indexLanguage1 = 1;
			indexLanguage2 = 0;
			
		}
			
		if (!schemahelper.isEncounter(q.getQuestions()[0][0])) {
			schemahelper.addEncounter(q.getQuestions()[0][0]);
			setViewNewWord();
		} else {
			setQuestion();
			imageview_progress_2.setEnabled(false);
		}
	}
	
	/*
	 * sets the view needed to present an new word
	 */
	public void setViewNewWord() {
		setContentView(R.layout.new_word);
		textview_new_word_1 = (TextView) findViewById(R.id.textViewNewWord1);
		textview_new_word_2 = (TextView) findViewById(R.id.textViewNewWord2);
		textview_new_word_1.setText(q.questions[1][0]);
		textview_new_word_2.setText(q.questions[0][0]);
		countDownTimer = new CountDownTimer(1000, 1000) {
			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFinish() {
				speak();
			}

		}.start();
		
	}

	/*
	 * sets the button with an "incorrect" layout (red)
	 */
	public void setWrong(Button b, TextView v) {
		int bottom = b.getPaddingBottom();
		int top = b.getPaddingTop();
		int right = b.getPaddingRight();
		int left = b.getPaddingLeft();
		b.setBackgroundResource(R.drawable.button_wrong);
		b.setTextColor(getResources().getColor(R.color.red));
		b.setPadding(left, top, right, bottom);
		b.setAnimation(shake);
		v.setVisibility(View.INVISIBLE);
		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
	}

	/*
	 * sets the button with a correct layout (green)
	 */
	public void setCorrect(Button b) {
		int bottom = b.getPaddingBottom();
		int top = b.getPaddingTop();
		int right = b.getPaddingRight();
		int left = b.getPaddingLeft();
		b.setBackgroundResource(R.drawable.button_correct);
		b.setTextColor(getResources().getColor(R.color.green));
		b.setTypeface(font_robo_m);
		b.setPadding(left, top, right, bottom);
	}

	/*
	 * resets the button to normal layout (white)
	 */
	public void setNormal(Button b) {
		int bottom = b.getPaddingBottom();
		int top = b.getPaddingTop();
		int right = b.getPaddingRight();
		int left = b.getPaddingLeft();
		b.setBackgroundResource(R.drawable.button);
		b.setTextColor(getResources().getColor(R.color.black));
		b.setTypeface(font_robo_l);
		b.setPadding(left, top, right, bottom);
	}

	/*
	 * Hide a specified button
	 */
	public void hideButton(Button b) {
		b.startAnimation(animationFadeOut);

		b.setVisibility(View.INVISIBLE);
	}

	/*
	 * Set all multiple choice buttons to visible
	 */
	public void showButtons() {
		findViewById(R.id.button1).startAnimation(animationFadeIn);
		findViewById(R.id.button2).startAnimation(animationFadeIn);
		findViewById(R.id.button3).startAnimation(animationFadeIn);
		findViewById(R.id.button4).startAnimation(animationFadeIn);

		findViewById(R.id.button1).setVisibility(View.VISIBLE);
		findViewById(R.id.button2).setVisibility(View.VISIBLE);
		findViewById(R.id.button3).setVisibility(View.VISIBLE);
		findViewById(R.id.button4).setVisibility(View.VISIBLE);

		findViewById(R.id.tvbutton1).setVisibility(View.VISIBLE);
		findViewById(R.id.tvbutton2).setVisibility(View.VISIBLE);
		findViewById(R.id.tvbutton3).setVisibility(View.VISIBLE);
		findViewById(R.id.tvbutton4).setVisibility(View.VISIBLE);

	}

	/*
	 * set the image so a progressbar effect occurs
	 */
	public void setImgProgress(int number) {
		String uri1 = "drawable/b" + number;
		String uri2 = "drawable/b" + (number + 1);
		int imageResource1 = getResources().getIdentifier(uri1, null, getPackageName());
		int imageResource2 = getResources().getIdentifier(uri2, null, getPackageName());
		Drawable image1 = getResources().getDrawable(imageResource1);
		Drawable image2 = getResources().getDrawable(imageResource2);
		imageview_progress_1.setImageDrawable(image1);
		imageview_progress_2.setImageDrawable(image2);
		imageview_progress_2.startAnimation(animationFadeIn);
	}

	/*
	 * set the image for pressing next
	 */
	public void setImgProgressNext() {
		String uri1 = "drawable/b" + count_1;
		int imageResource1 = getResources().getIdentifier(uri1, null, getPackageName());
		Drawable image1 = getResources().getDrawable(imageResource1);
		String uri2 = "drawable/b" + 10;
		int imageResource2 = getResources().getIdentifier(uri2, null, getPackageName());
		Drawable image2 = getResources().getDrawable(imageResource2);
		imageview_progress_1.setImageDrawable(image1);
		imageview_progress_2.setImageDrawable(image2);
		imageview_progress_2.startAnimation(animationFadeIn);

	}

	/*
	 * set a new question & timer
	 */
	public void setQuestion() {
		count_1 = 0;
		countDownTimer = new CountDownTimer(9000, 1000) {
			@Override
			public void onTick(long millisUntilFinished_) {
				setImgProgress(count_1);
				count_1++;
			}

			@Override
			public void onFinish() {
				wrongAnswerTimeout(getCurrentTime());
			}
		}.start();
		textview_question.setText(q.questions[indexLanguage2][0]);
		Collections.shuffle(Arrays.asList(order)); // shuffle order
		for (int i = 0; i < buttons_answer.length; i++) {
			buttons_answer[i].setText(q.questions[indexLanguage1][order[i]]);
			buttons_answer[i].setEnabled(true); // set button enabled
			setNormal(buttons_answer[i]); // background
		}
		textViewStack.setText("" + spacer.getNumberInStack() + "/" + section.size() + " " + getString(R.string.stack));

		spacer.startOfEventTime = System.currentTimeMillis();
	}

	private void showDialog() {
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					// Yes button clicked
					finish();
					break;

				case DialogInterface.BUTTON_NEGATIVE:
					// No button clicked
					stop = false;
					break;
				}
			}
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.complete))
				.setPositiveButton(getString(R.string.yes), dialogClickListener)
				.setNegativeButton(getString(R.string.no), dialogClickListener).show();
	}



	/*
	 * user clicks on next button from newWordView
	 */
	public void clickNextNew(View view) {
		setViewMultipleChoice();
		setQuestion();
		imageview_progress_2.setEnabled(false);
	}

	/*
	 * if the answer of the user is correct
	 */
	public void correctAnswer(int answer, long time) {
		for (int i = 0; i < buttons_answer.length; i++) {
			buttons_answer[i].setEnabled(false);
			if (i != answer) {
				hideButton(buttons_answer[i]);
			}
		}
		setCorrect(buttons_answer[answer]);
		countDownTimer = new CountDownTimer(1000, 1000) {
			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFinish() {
				clickNext(null);
			}

		}.start();
		// imageview_progress_2.setEnabled(true);
		spacer.updateAnswer(true, time);
	}

	/*
	 * if the answer of the user is wrong theres a 5 seconds waiting time
	 */
	public void wrongAnswerWait() {
		count_2 = 0;
		countDownTimer = new CountDownTimer(6100, 1000) {
			@Override
			public void onTick(long millisUntilFinished_) {
				if (count_2 > 0) {
					textview_time.setText("" + (6 - count_2));
				}
				count_2++;
			}

			@Override
			public void onFinish() {
				textview_time.setText("");
				// setImgProgressNext();
				clickNext(null);
				// imageview_progress_2.setEnabled(true);
			}
		}.start();
	}

	/*
	 * if no answer is given there is a 5 seconds waiting time and a next button
	 */
	public void noAnswerWait() {
		count_2 = 0;
		countDownTimer = new CountDownTimer(6100, 1000) {
			@Override
			public void onTick(long millisUntilFinished_) {
				if (count_2 > 0) {
					textview_time.setText("" + (6 - count_2));
				}
				count_2++;
			}

			@Override
			public void onFinish() {
				textview_time.setText("");
				setImgProgressNext();
				imageview_progress_2.setEnabled(true);
			}
		}.start();
	}

	/*
	 * user answers the question incorrect
	 */
	public void wrongAnswer(int answer, long time) {
		setWrong(buttons_answer[answer], tvbutton_answer[answer]);
		for (int i = 0; i < buttons_answer.length; i++) {
			buttons_answer[i].setEnabled(false);
			if (order[i] == 0) {
				setCorrect(buttons_answer[i]);
			}
			if (i != answer && order[i] != 0) {
				hideButton(buttons_answer[i]);
			}
			buttons_answer[answer].setText(q.questions[indexLanguage1][order[answer]] + " (" + q.questions[indexLanguage2][order[answer]] + ")");
		}
		wrongAnswerWait();
		spacer.updateAnswer(false, time);
	}

	/*
	 * wrong answer because of timeout
	 */
	public void wrongAnswerTimeout(long time) {
		for (int i = 0; i < buttons_answer.length; i++) {
			buttons_answer[i].setEnabled(false);
			if (order[i] == 0) {
				setCorrect(buttons_answer[i]);
			} else {
				hideButton(buttons_answer[i]);
			}
		}
		noAnswerWait();
		spacer.updateAnswer(false, time);
	}

	/*
	 * determine if answer is correct
	 */
	public void clickAnswer(int answer, long time) {
		speak();
		

		countDownTimer.cancel();
		if (order[answer] == 0) {
			correctAnswer(answer, time);
		} else {
			wrongAnswer(answer, time);
		}
	}

	public void clickAnswerA(View view) {
		answerTime = getCurrentTime();
		clickAnswer(0, answerTime);
	}

	public void clickAnswerB(View view) {
		answerTime = getCurrentTime();
		clickAnswer(1, answerTime);
	}

	public void clickAnswerC(View view) {
		answerTime = getCurrentTime();
		clickAnswer(2, answerTime);
	}

	public void clickAnswerD(View view) {
		answerTime = getCurrentTime();
		clickAnswer(3, answerTime);
	}

	public long getCurrentTime() {
		return System.currentTimeMillis();
	}

	@Override
	public void onBackPressed() {
		if (doubleBackToExitPressedOnce) {
			try {
				countDownTimer.cancel();
			} catch (Exception ex) {

			}
			super.onBackPressed();
			return;
		}
		this.doubleBackToExitPressedOnce = true;
		Toast.makeText(this, getString(R.string.pessback), Toast.LENGTH_SHORT).show();
		new Handler().postDelayed(new Runnable() {

			public void run() {
				doubleBackToExitPressedOnce = false;

			}
		}, 2000);
	}

	private boolean useTTS;

	public void onInit(int status) {
		// TODO Auto-generated method stub
		// TTS is successfully initialized
		if (status == TextToSpeech.SUCCESS) {
			useTTS = true;
			// Setting speech language
			Locale loc = new Locale("eng", "ENG");
			int result = tts.setLanguage(loc);
			// If your device doesn't support language you set above
			if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
				showDialogTTS();
				//soundOn.setVisible(false);
				//soundOff.setVisible(false);
				
				// Cook simple toast message with message
				// Toast.makeText(this, "Language not supported",
				// Toast.LENGTH_LONG).show();
				// Log.e("TTS", "Language is not supported");
			}

			else {

			}
			// TTS is not initialized properly
		} else {
			showDialogTTS();
			
			useTTS = false;
			//soundOn.setVisible(false);
			//soundOff.setVisible(false);
			
			// Toast.makeText(this, "TTS Initilization Failed",
			// Toast.LENGTH_LONG).show();
			// Log.e("TTS", "Initilization Failed");
		}
	}

	@Override
	public void onDestroy() {
		// Don't forget to shutdown tts!
		if (tts != null) {
			tts.stop();
			tts.shutdown();
		}
		super.onDestroy();
	}

	MenuItem soundOn;
	MenuItem soundOff;
	boolean sound;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Used to put dark icons on light action bar
		SharedPreferences sp = getSharedPreferences("my_db", Context.MODE_PRIVATE);

		sound = sp.getBoolean("sound", true);

		soundOn = menu.add("Sound off");
		soundOn.setIcon(R.drawable.volume_on);
		soundOn.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		soundOn.setVisible(sound);

		soundOff = menu.add("Sound on");
		soundOff.setIcon(R.drawable.volume_mute);
		soundOff.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		soundOff.setVisible(!sound);
		
        menu.add("Help").setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);


		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// This uses the imported MenuItem from ActionBarSherlock
		// Toast.makeText(this, "Got click: " + item.toString(),
		// Toast.LENGTH_SHORT).show();
		if (item.getTitle() == "Sound off") {
			soundOn.setVisible(false);
			soundOff.setVisible(true);
			sound = false;
		}
		if (item.getTitle() == "Sound on") {
			soundOn.setVisible(true);
			soundOff.setVisible(false);
			sound = true;
		}
        if(item.getTitle()=="Help"){
    		Intent intent = new Intent(this, WalkthroughActivity.class);
    		intent.putExtra("filePrefix", imageFilePrefix.toString());
    		intent.putExtra("nrOfPages", nrOfWalkthroughPages);
    		startActivity(intent);
        }
		SharedPreferences sp = getSharedPreferences("my_db", Context.MODE_PRIVATE);
		Editor e = sp.edit();
		e.putBoolean("sound", sound);
		e.commit();

		return true;
	}
	
	
	

	public void speak() {
		if (useTTS && sound) {
			tts.speak(q.questions[0][0], TextToSpeech.QUEUE_FLUSH, null);
		}
	}
	
	private void showDialogTTS() {
		SharedPreferences sp = getSharedPreferences("my_db", Context.MODE_PRIVATE);

		if(sp.getBoolean("tts", true)){
		
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case DialogInterface.BUTTON_POSITIVE:
					// Yes button clicked
			        Intent installIntent = new Intent();
			        installIntent.setAction(
			        TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
			        startActivity(installIntent);	
					break;

				case DialogInterface.BUTTON_NEGATIVE:
					// No button clicked
					
					break;
				
				case DialogInterface.BUTTON_NEUTRAL:
					SharedPreferences sp = getSharedPreferences("my_db", Context.MODE_PRIVATE);
					Editor e = sp.edit();
					e.putBoolean("tts", false);
					e.commit();
					break;
					
					
				}
				
				
				
				
			}
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.notts)).setNeutralButton(getString(R.string.notagain), dialogClickListener)
				.setPositiveButton(getString(R.string.yes), dialogClickListener)
				.setNegativeButton(getString(R.string.no), dialogClickListener).show();
		}
	}
	

}